import jdk.nashorn.internal.ir.Block;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-10-25
 * Time: 22:49
 */
public class MyThreadPool {
    //任务直接用Runnable,不用另外创建类了
    //用阻塞队列来组织任务
    private BlockingQueue<Runnable> queue=new LinkedBlockingQueue<>();

    //用来描述线程的类
    static class Worker extends Thread{
        private BlockingQueue<Runnable> queue=null;
        //利用构造方法获取任务队列
        public Worker(BlockingQueue<Runnable> queue){
            this.queue=queue;
        }

        @Override
        public void run() {
            while(true){
                try {
                    //如果队列为空则阻塞
                    Runnable runnable=queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    //用数组来当作池存储线程
    List<Thread> list=new ArrayList<>();
    //构造方法中创建若干线程放到线程池中
    public MyThreadPool(int n){
            for(int i=0;i<n;i++){
                Worker worker=new Worker(this.queue);
                //注意不要忘记start
                worker.start();
                //加入线程池中
                list.add(worker);
            }
    }

    //提交任务
    public void submit(Runnable runnable)  {
        try {
            this.queue.put(runnable);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        MyThreadPool pool=new MyThreadPool(10);
        for(int i=0;i<100;i++){
            //submit了100次,相当于100个任务进入了任务队列,每个线程分一些,很快就执行完了
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("myThreadPool");
                }
            });
        }
    }
}
